import Vue from 'vue'
import Vuex from 'vuex'
import http from '@/utils/request.js'
import SockJs from 'sockjs-client'
import Stomp from 'stompjs'
import { Notification } from 'element-ui'

Vue.use(Vuex)

const now = new Date();

const store =  new Vuex.Store({
  state: {
    //菜单列表
    routes: [],
    //除登录用户外的所有用户
    admins:[],
    //所有消息集合
    sessions:{},
    //当前选中的用户
    currentSession:null,
    //当前登录用户
    currentAdmin:null,
    filterKey:'',
    //stomp对象
    stomp:null,
    //未读消息[小红点]
    dot:{}
  },
  mutations: {
    //初始化菜单
    initRoutes(state,data){
        state.routes = data;
    },

    changeCurrentSession (state,data) {
        state.currentSession = data;
        Vue.set(state.dot,`${state.currentAdmin.username}#${state.currentSession.username}`,false);
    },
    addMessage (state,msg) {
        if(state.currentAdmin == null) return;
        if(!state.sessions[`${state.currentAdmin.username}#${msg.to}`]){
            // console.log(state.sessions)
            Vue.set(state.sessions,`${state.currentAdmin.username}#${msg.to}`,[]);
        } 
        state.sessions[`${state.currentAdmin.username}#${msg.to}`].push({
            content:msg.content,
            date:new Date(),
            type:msg.type,
            self:!msg.notSelf
        })
    },
    INIT_DATA (state) {
        //浏览器本地的历史聊天记录
        let data = localStorage.getItem('vue-chat-session');
        //console.log(data)
        if (data) {
            state.sessions = JSON.parse(data);
        }
    },

    INIT_ADMINS(state,value){
        state.admins = value;
    },
    INIT_CURRENTADMIN(state,value){
        state.currentAdmin = value;
    }
  },


    actions:{
        //连接websocket
        chatConnect(context){
            //创建并设置stomp对象
            context.state.stomp = Stomp.over(new SockJs('/ws/ep'));
            let token = window.sessionStorage.getItem("tokenStr");
            //通过stomp对象建立连接
            context.state.stomp.connect({'token':JSON.parse(token)},success=>{
                //接收广播
                context.state.stomp.subscribe("/user/queue/chat",msg=>{
                    console.log("连接websocket返回的消息",msg);
                    let message = JSON.parse(msg.body);
                    //没在任何通讯框或者不是与选择的通讯框聊天时给出消息提示框
                    if(!context.state.currentSession || message.from != context.state.currentSession.username){
                        Notification.info({
                            title: `【${message.fromNickName}】给你发送了一条消息`,
                            message: message.content.length > 10 ? message.content.substr(0,10)+'...' : message.content,
                            position: 'bottom-right'
                        });
                        Vue.set(context.state.dot,`${context.state.currentAdmin.username}#${message.from}`,true);
                        // console.log("dot",context.state.dot)
                    }
                    message.notSelf = true;
                    message.to = message.from;
                    context.commit("addMessage",message);
                });
            },error=>{})
        },
        //获取所有管理员列表
        initData (context) {
            context.commit('INIT_DATA');
            http({
                method:'get',
                url:'/chat/admin'
            }).then(resp=>{
                if(resp){
                    context.commit('INIT_ADMINS',resp);
                }
            })
        },
        //获取当前登录用户信息
        getCurrentAdmin(context){
            http({
                method:'get',
                url:'/admin/info'
            }).then(resp=>{
                // console.log("获取当前用户：",resp);
                if(resp && resp.code == 0){
                    context.commit('INIT_CURRENTADMIN',JSON.parse(resp.data));
                }
            })
        }
    }
})


store.watch(function (state) {
    return state.sessions
},function (val) {
    // console.log('CHANGE: ', val);
    localStorage.setItem('vue-chat-session', JSON.stringify(val));
},{
    deep:true/*这个貌似是开启watch监测的判断,官方说明也比较模糊*/
})

export default store;